//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using Eas.WebCrawler.Model.Core;
using Eas.WebCrawler.Interfaces;

namespace Eas.WebCrawler.Model.Actions {
    internal abstract class SleepingAction : ProcessingAction {
        public delegate void SleepDelegate(int milliseconds);
        public static SleepDelegate CreateSleepDelegate() { return delegate(int milliseconds) { System.Threading.Thread.Sleep(milliseconds); }; }

        private SleepDelegate _SleepDelegate = CreateSleepDelegate();

        #region ProcessingAction Members

        public abstract ActionId ActionId { get; }
        public abstract WorkerState WorkerState { get;}

        public void PerformCompletingAction(WorkerContext context, BaseProcessingState state, IAsyncResult result) {
            context.EventReporter.ReportTrace(Eas.WebCrawler.Interfaces.TraceLevel.Annoying, state, "Calling end sleep.");
            context.StateTracker.CloseResult(result);
            _SleepDelegate.EndInvoke(result);
        }

        public IAsyncResult BeginAction(WorkerContext context, Eas.WebCrawler.Model.Core.BaseProcessingState state, AsyncCallback callback) {
            context.EventReporter.ReportTrace( Eas.WebCrawler.Interfaces.TraceLevel.Annoying, state, "Calling BeginSleep");
            IAsyncResult result = _SleepDelegate.BeginInvoke(context.WebCrawlerContext.SleepTimeInMilliseconds, callback, state);
            context.EventReporter.ReportTrace(Eas.WebCrawler.Interfaces.TraceLevel.Annoying, state, "Returned from BeginSleep");
            context.StateTracker.OpenResult(result, this);
            return result;
        }

        public virtual ProcessingAction EndAction(WorkerContext context, Eas.WebCrawler.Model.Core.BaseProcessingState state, IAsyncResult result) {
            PerformCompletingAction(context, state, result);
            return this;
        }

        #endregion
    }
}
